from PIL import Image, ImageDraw, ImageFont
import pandas as pd
import numpy as np

# 读取地图数据
map_img = Image.open('fishbot_map.pgm')

# 调整图片大小到1920x1080
target_width = 1920
target_height = 1080
map_img = map_img.resize((target_width, target_height), Image.LANCZOS)

# 转换为RGB模式便于绘制彩色内容
map_rgb = map_img.convert('RGB')

# 创建绘图对象
draw = ImageDraw.Draw(map_rgb)

# 读取场景数据
df = pd.read_csv('scene_data_20241110_120625.csv')

# 定义关键词映射
keyword_map = {
    '工业': 'MACHINE',
    '容器': 'CONTAINER',
    '室内': 'INDOOR',
    '家具': 'FURNITURE',
    '人物': 'PERSON',
    '浴室': 'BATH'
}

# 地图坐标转换为像素坐标的函数
def coord_to_pixel(x, y):
    origin_x, origin_y = -5.27, -6.53
    map_width = 12.0  # 地图实际宽度(米)
    map_height = 9.0  # 地图实际高度(米)
    
    # 计算比例
    scale_x = target_width / map_width
    scale_y = target_height / map_height
    
    # 转换坐标
    pixel_x = int((x - origin_x) * scale_x)
    pixel_y = int(target_height - (y - origin_y) * scale_y)
    
    return pixel_x, pixel_y

# 加载字体(更大的字号)
try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 24)
except:
    font = ImageFont.load_default()

# 绘制标记和描述
for _, row in df.iterrows():
    # 转换坐标
    x, y = coord_to_pixel(row['X坐标'], row['Y坐标'])
    
    # 根据描述选择关键词
    keyword = 'INDOOR'  # 默认关键词
    for key, value in keyword_map.items():
        if key in row['描述']:
            keyword = value
            break
    
    # 计算文本宽度以居中显示
    keyword_bbox = draw.textbbox((0, 0), keyword, font=font)
    keyword_width = keyword_bbox[2] - keyword_bbox[0]
    text_x = x - keyword_width // 2
    
    # 绘制关键词标记
    draw.text((text_x, y-12), keyword, fill=(255, 0, 0), font=font)
    
    # 提取描述文本(取前20个字)
    desc = row['描述'][:20].replace('\n', ' ') + '...'
    desc_bbox = draw.textbbox((0, 0), desc, font=font)
    desc_width = desc_bbox[2] - desc_bbox[0]
    desc_x = x - desc_width // 2
    
    # 绘制描述文本
    draw.text((desc_x, y+12), desc, fill=(0, 0, 255), font=font)

# 添加图例(放在右上角)
legend_x = target_width - 300
legend_y = 50
draw.text((legend_x, legend_y-30), "Map Legend:", fill=(0, 0, 0), font=font)
for key, value in keyword_map.items():
    draw.text((legend_x, legend_y), f"{value}: {key}", fill=(0, 0, 0), font=font)
    legend_y += 30

# 保存高分辨率结果
map_rgb.save('scene_map.png', dpi=(300, 300))
